package ua.com.alus.resvac.crm.services.spring;


import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ua.com.alus.resvac.crm.domen.dao.VacancyDao;
import ua.com.alus.resvac.crm.domen.entities.Vacancy;
import ua.com.alus.resvac.crm.domen.entities.VacancyFile;
import ua.com.alus.resvac.crm.domen.prototype.DocType;

import java.util.List;

/**
 * Vacancy Service Implementation
 * <p/>
 * Created by Usatov Alexey
 */
public class VacancyServiceImpl implements VacancyService {
    private VacancyDao vacancyDao;
    private LuceneService luceneService;

    public void setLuceneService(LuceneService luceneService) {
        this.luceneService = luceneService;
    }

    public VacancyDao getVacancyDao() {
        return vacancyDao;
    }

    public void setVacancyDao(VacancyDao vacancyDao) {
        this.vacancyDao = vacancyDao;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveVacancy(Vacancy vacancy) {
        Vacancy mergedVacancy = vacancyDao.merge(vacancy);
        try {
            luceneService.indexRecord(mergedVacancy);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Vacancy getVacancy(String vacancyUuid) {
        return vacancyDao.findById(vacancyUuid);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void deleteVacancyFile(String uuid) {
        getVacancyDao().getEntityManager().createNativeQuery(VacancyFile.NATIVE_DELETE_VACANCY_FILE).
                setParameter(1, uuid).executeUpdate();
        try {
            luceneService.deleteRecord(uuid, DocType.VACANCY);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public List<Vacancy> getVacancies(String accountUuid) {
        return getVacancyDao().getEntityManager().createNamedQuery(Vacancy.SELECT_VACANCY_BY_ACCOUNT_UUID).
                setParameter("accountUuid", accountUuid).getResultList();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<String> getVacancyFilesUuid(String vacancyUuid) {
        return getVacancyDao().getEntityManager().createNativeQuery(VacancyFile.NATIVE_SELECT_VACANCY_FILES_UUID)
                .setParameter(1, vacancyUuid).getResultList();
    }
}
